package io.github.karino2.pngnote;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import io.github.karino2.pngnote.book.FastFile;
import io.github.karino2.pngnote.book.BookIO;
import io.github.karino2.pngnote.ui.CanvasBoox;
import io.github.karino2.pngnotemod.R;

public class BookActivity extends AppCompatActivity {
    private Uri dirUrl;
    private int initialPageIdx;
    private FastFile bookDir$delegate;// = bookDir_init();
    FastFile bookDir_init() {
        Context var10001 = (Context)BookActivity.this;
        Uri var1 = BookActivity.this.dirUrl;
        Uri var10002;
        if (var1 != null) {
            var10002 = var1;
        } else {
            var10002 = null;
        }
        return FastFile.fromTreeUri(var10001, var10002);
    };

    private BookIO bookIO$delegate;// = bookIO_init();
    private BookIO bookIO_init() {
        ContentResolver var1 = BookActivity.this.getContentResolver();
        return new BookIO(var1);
    }

    private Book _book;
    private int pageIdx$delegate;// = pageIdx_init();
    private int pageIdx_init() {
        return BookActivity.this.initialPageIdx;
    }

    private void onCreateAct() {
        bookDir$delegate = bookDir_init();
        bookIO$delegate = bookIO_init();
        pageIdx$delegate = pageIdx_init();
    }
    private void onPageIdxChange() {
        canvas.onPageIdx(getPageIdx(), new CanvasBoox.OnLoadBitmapListener() {
            @Override
            public Bitmap onLoadBitmap(int idx) {
                BookIO bookIO = getBookIO();
                Bitmap it = null;
                it = bookIO.loadBitmapOrNull(getBook().getPage(idx));
                isDirty = false;
                pageBmp = it;
                return it;
            }
        });
        onUpdatePidxPnum();
    }

    private int pageNum = 0;
    private boolean canRedo = false;
    private boolean canUndo = false;
    private int undoCount = 0;
    private int redoCount = 0;
    private long lastWritten = -1L;
    private Bitmap emptyBmp;
    private Bitmap pageBmp;
    private boolean isDirty;
    private static final long SAVE_INTERVAL_MILL = 5000L;
    private static final ReentrantLock bitmapLock = new ReentrantLock();

    private FastFile getBookDir() {
        return this.bookDir$delegate;
    }

    private BookIO getBookIO() {
        return this.bookIO$delegate;
    }

    private void set_book(Book newbook) {
        int var10001 = 0;
        this._book = newbook;
        if (newbook != null) {
            List var2 = newbook.getPages();
            if (var2 != null) {
                int var3 = var2.size();
                var10001 = var3;
            }
        }
        this.pageNum = var10001;
        this.onUpdatePidxPnum();
    }

    private Book getBook() {
        Book var1 = this._book;
        if (var1 != null) {
            Book it = var1;
            return it;
        } else {
            var1 = this.getBookIO().loadBook(this.getBookDir());
            Book it = var1;
            this.set_book(it);
            return it;
        }
    }

    private void showMessage(String msg) {
        Toast.makeText((Context)this, (CharSequence)msg, Toast.LENGTH_LONG).show();
    }

    private int getPageIdx() {
        return this.pageIdx$delegate;
    }

    private void notifyBitmapUpdate(Bitmap newBmp) {
        this.isDirty = true;
        this.lastWritten = this.getCurrentMills();
        this.pageBmp = newBmp;
        this.lazySave();
    }

    private void notifyUndoStateChanged(boolean canUndo1, boolean canRedo1) {
        this.canUndo = canUndo1;
        this.canRedo = canRedo1;
    }

    private long getCurrentMills() {
        return (new Date()).getTime();
    }

    private void savePage(final int pageIdx, Bitmap pageBmp) {
        this.getBookIO().saveBitmap(this.getBook().getPage(pageIdx), pageBmp);
        new Thread(new Runnable() {
            @Override
            public void run() {
                BookActivity.this.set_book(BookActivity.this.getBook().assignNonEmpty(pageIdx));
            }
        }).start();
    }

    private void savePageInMain(int pageIdx, Bitmap pageBmp) {
        this.getBookIO().saveBitmap(this.getBook().getPage(pageIdx), pageBmp);
        this.set_book(this.getBook().assignNonEmpty(pageIdx));
    }

    private void lazySave() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(BookActivity.this.SAVE_INTERVAL_MILL);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (BookActivity.this.isDirty && BookActivity.this.getCurrentMills() - BookActivity.this.lastWritten >= BookActivity.this.SAVE_INTERVAL_MILL) {
                    BookActivity.this.isDirty = false;
                    Lock var3 = (Lock)BookActivity.getBitmapLock();
                    BookActivity var4 = BookActivity.this;
                    var3.lock();

                    Bitmap var10;
                    try {
                        Bitmap var11 = var4.pageBmp;
                        Bitmap bmp = var11;
                        var10 = bmp.copy(bmp.getConfig(), false);
                    } finally {
                        var3.unlock();
                    }

                    BookActivity var12 = BookActivity.this;
                    int var14 = BookActivity.this.getPageIdx();
                    var12.savePage(var14, var10);
                }
            }
        }).start();
    }

    private void ensureSave() {
        if (this.isDirty) {
            this.isDirty = false;
            int var1 = this.getPageIdx();
            Bitmap var10002 = this.pageBmp;
            this.savePageInMain(var1, var10002);
        }
    }

    protected void onStop() {
        this.ensureSave();
        super.onStop();
    }

    //FIXME: remove RequiresApi
    @RequiresApi(26)
    private void share() {
        this.ensureSave();
        if (this.pageBmp != null) {
            Closeable var2 = null;
            File path = null;
            try {
                path = File.createTempFile("share", ".png", this.getCacheDir());
                var2 = new FileOutputStream(path);
                FileOutputStream it = (FileOutputStream)var2;
                this.pageBmp.compress(Bitmap.CompressFormat.PNG, 100, (OutputStream)it);
                it.flush();
            } catch (Throwable e) {
                e.printStackTrace();
                path = null;
            } finally {
                try {
                    if (var2 != null) {
                        var2.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (path != null) {
                Uri u = FileProvider.getUriForFile((Context) this, this.getApplicationContext().getPackageName() + ".provider", path);
                this.shareImageUri(u);
            }
        }
    }

    private void shareImageUri(Uri uri) {
        Intent intent = new Intent("android.intent.action.SEND");
        intent.putExtra("android.intent.extra.STREAM", (Parcelable)uri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setType("image/png");
        this.startActivity(intent);
    }

    private void addNewPageAndGo() {
        this.ensureSave();
        Bitmap var1;
        Bitmap ebmp;
        boolean var4;
        if (this.emptyBmp == null) {
            var1 = this.pageBmp;
            if (var1 != null) {
                ebmp = var1;
                var4 = false;
                Bitmap var5 = Bitmap.createBitmap(ebmp.getWidth(), ebmp.getHeight(), Bitmap.Config.ARGB_8888);
                Bitmap $this$addNewPageAndGo_u24lambda_u244_u24lambda_u243 = var5;
                int var8 = 0;
                $this$addNewPageAndGo_u24lambda_u244_u24lambda_u243.eraseColor(-1);
                this.emptyBmp = var5;
            }
        }

        this.set_book(this.getBook().addPage());
        var1 = this.emptyBmp;
        int var10001;
        if (var1 != null) {
            ebmp = var1;
            var4 = false;
            var10001 = this.pageNum;
            this.savePageInMain(var10001 - 1, ebmp);
        }

        this.pageIdx$delegate = this.pageNum - 1;
        onPageIdxChange();
    }

    private void gotoFirstPage() {
        this.ensureSave();
        this.pageIdx$delegate = 0;
        onPageIdxChange();
    }

    private void gotoLastPage() {
        this.ensureSave();
        this.pageIdx$delegate = this.pageNum - 1;
        onPageIdxChange();
    }

    private void gotoPrevPage() {
        this.ensureSave();
        int var1 = this.getPageIdx();
        if (var1 >= 1) {
            this.pageIdx$delegate = var1 - 1;
            onPageIdxChange();
        }
    }

    private void gotoNextPage() {
        this.ensureSave();
        int var1 = this.getPageIdx();
        this.pageIdx$delegate = var1 + 1;
        onPageIdxChange();
    }

    private void gotoGridPage() {
        Intent var1 = new Intent((Context)this, PageGridActivity.class);
        Intent it = var1;
        Uri var4 = this.dirUrl;
        Uri var10001;
        if (var4 != null) {
            var10001 = var4;
        } else {
            var10001 = null;
        }
        it.setData(var10001);
        this.startActivity(it);
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            Intent it = intent;
            int var4 = 0;
            this.handlePageIdxArg(it);
        }

    }

    private TextView textViewPageInfo;
    CanvasBoox canvas;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = this.getIntent();
        if (intent != null) {
            this.dirUrl = intent.getData();
            this.handlePageIdxArg(intent);
        }

        setContentView(R.layout.activity_book);
        //FIXME:
        ActionBar topAppBar = getSupportActionBar();
        topAppBar.setIcon(R.mipmap.ic_launcher);
        topAppBar.setHomeButtonEnabled(true);
        topAppBar.setDisplayHomeAsUpEnabled(true);
        if (!Config.USE_ACTIONBAR) {
            topAppBar.hide();
        }
        findViewById(R.id.buttonBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.buttonPen).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onPen();
            }
        });
        findViewById(R.id.buttonEraser).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onEraser();
            }
        });
        findViewById(R.id.buttonUndo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onUndo();
            }
        });
        findViewById(R.id.buttonRedo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onRedo();
            }
        });
        findViewById(R.id.buttonGrid).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoGridPage();
            }
        });
        findViewById(R.id.buttonFirstPage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoFirstPage();
            }
        });
        findViewById(R.id.buttonPrevPage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoPrevPage();
            }
        });
        findViewById(R.id.buttonNextPage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoNextPage();
            }
        });
        findViewById(R.id.buttonLastPage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoLastPage();
            }
        });
        findViewById(R.id.buttonAddPage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addNewPageAndGo();
            }
        });
        findViewById(R.id.buttonShare).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    share();
                }
            }
        });
        textViewPageInfo = (TextView) findViewById(R.id.textViewPageInfo);











        //FIXME:throw new RuntimeException("not implemented");
        canvas = (CanvasBoox) findViewById(R.id.canvas);
        try {
            Bitmap initBmp = getBookIO().loadBitmapOrNull(getBook().getPage(getPageIdx()));
            Bitmap bgBmp = getBookIO().loadBgOrNull(getBook());
            canvas.init(initBmp, bgBmp, initialPageIdx);
        } catch (Throwable eee) {
            eee.printStackTrace();
        }
        canvas.setClipToOutline(true);
        canvas.setOnUpdateListener(new CanvasBoox.OnUpdateBmpListener() {
            @Override
            public void onUpdateBmp(Bitmap bmp) {
                notifyBitmapUpdate(bmp);
            }
        });
        canvas.setOnUndoStateListener(new CanvasBoox.OnUndoStateListener() {
            @Override
            public void onUndoState(Boolean undo, Boolean redo) {
                notifyUndoStateChanged(undo, redo);
            }
        });

        onCreateAct();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.book, menu);
        return true;
    }

    boolean isEraser = false;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.pen:
                onPen();
                break;

            case R.id.eraser:
                onEraser();
                break;

            case R.id.undo:
                onUndo();
                break;

            case R.id.redo:
                onRedo();
                break;

            case R.id.grid:
                gotoGridPage();
                break;

            case R.id.firstPage:
                gotoFirstPage();
                break;

            case R.id.prevPage:
                gotoPrevPage();
                break;

            case R.id.nextPage:
                gotoNextPage();
                break;

            case R.id.lastPage:
                gotoLastPage();
                break;

            case R.id.addPage:
                addNewPageAndGo();
                break;

            case R.id.share:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    share();
                }
                break;
        }
        return true;
    }
    private void onPen() {
//        if (item.isChecked()) {
//            item.setChecked(false);
//            isEraser = true;
//            canvas.penOrEraser(!isEraser);
//        } else {
//            item.setChecked(true);
//            isEraser = false;
//            canvas.penOrEraser(!isEraser);
//        }
        //FIXME:
        if (!isEraser) {
            isEraser = true;
            canvas.penOrEraser(!isEraser);
        } else {
            isEraser = false;
            canvas.penOrEraser(!isEraser);
        }
    }
    private void onEraser() {
//        if (item.isChecked()) {
//            item.setChecked(false);
//            isEraser = false;
//            canvas.penOrEraser(!isEraser);
//        } else {
//            item.setChecked(true);
//            isEraser = true;
//            canvas.penOrEraser(!isEraser);
//        }
        //FIXME:
        if (isEraser) {
            isEraser = false;
            canvas.penOrEraser(!isEraser);
        } else {
            isEraser = true;
            canvas.penOrEraser(!isEraser);
        }
    }
    private void onUndo() {
        undoCount = undoCount + 1;
        canvas.undo(undoCount);
    }
    private void onRedo() {
        redoCount = redoCount + 1;
        canvas.redo(redoCount);
    }
    private void onUpdatePidxPnum() {
        if (textViewPageInfo != null) {
            textViewPageInfo.post(new Runnable() {
                @Override
                public void run() {
                    textViewPageInfo.setText("" + getPageIdx() + "/" + pageNum);
                };
            });
        }
    }


    private void handlePageIdxArg(Intent intent) {
        int argPageIdx = intent.getIntExtra("PAGE_IDX", -1);
        if (argPageIdx != -1) {
            this.initialPageIdx = argPageIdx;
        }
    }

    public static ReentrantLock getBitmapLock() {
        return BookActivity.bitmapLock;
    }
}
